package com.example.smartall.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.smartall.R;
import com.example.smartall.adapter.ServiceRecycleAdapter;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.diaglog.SearchServiceDialog;
import com.example.smartall.entity.ServiceBean;
import com.example.smartall.fragment.base.BaseFragment;
import com.example.smartall.ui.ActActivity;
import com.example.smartall.ui.HospitalActivity;
import com.example.smartall.ui.HouseActivity;
import com.example.smartall.ui.JobHuntingActivity;
import com.example.smartall.ui.OrderActivity;
import com.example.smartall.ui.PaymentActivity;
import com.example.smartall.ui.SubwayActivity;
import com.example.smartall.ui.CarParkingActivity;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

/**
 * @Author: abbas
 * @CreateDate: 2022/1/30
 * @Description: 别吐槽我，我今天再回来看这个代码也看了很久
 * <p>
 * <p>
 * 全部服务页面
 * （1）在全部服务页面，页面具有搜索服务应用功能，输入服务名称点击确定按钮，会弹出搜索结果对话框，点击搜索结果图标，跳转至对应功能页面。
 * （2）列表结构显示类别名称，点击左侧对应分类名称，右侧显示该类别对应的服务，以宫格的形式进行排列，服务应用具有图标和服务名称。
 * <p>
 * ！！！！类别之间利用灰色直线分隔显示。！！！！
 * <p>
 * 和我布局应该是有区别的
 */

/**
 * @Date: 2022/2/13
 * @Description: 重新搞布局
 */

public class AllServiceFragment extends BaseFragment {

    private List<ServiceBean.RowsBean> serviceBean = new ArrayList<>();
    private List<String> serviceTypes = new ArrayList<>();
    private BaseAdapter baseAdapter;

    private ScrollView sc;
    private EditText etSearch;
    private Button btSearch;
    private ListView lvService;
    private LinearLayout ln1;
    private TextView tv1;
    private RecyclerView rv1;
    private LinearLayout ln2;
    private TextView tv2;
    private RecyclerView rv2;
    private LinearLayout ln3;
    private TextView tv3;
    private RecyclerView rv3;
    private List<LinearLayout> ln = new ArrayList<>();

    private Map<String, Class> params;

    private MHandler handler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        handler = new MHandler();
        View view = inflater.inflate(R.layout.fragment_all_service, container, false);
        init(view);
        initEvent();
        getAllService();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (params == null){
            params = new HashMap<>();
            params.put("城市地铁", SubwayActivity.class);
            params.put("门诊预约", HospitalActivity.class);
            params.put("停哪儿", CarParkingActivity.class);
            params.put("外卖订餐", OrderActivity.class);
            params.put("生活缴费", PaymentActivity.class);
            params.put("找工作", JobHuntingActivity.class);
            params.put("找房子", HouseActivity.class);
            params.put("活动管理", ActActivity.class);
        }
    }

    private void init(View view) {
        sc = (ScrollView) view.findViewById(R.id.sc);
        etSearch = (EditText) view.findViewById(R.id.et_search);
        btSearch = (Button) view.findViewById(R.id.bt_search);
        lvService = (ListView) view.findViewById(R.id.lv_service);
        ln1 = (LinearLayout) view.findViewById(R.id.ln1);
        tv1 = (TextView) view.findViewById(R.id.tv1);
        rv1 = (RecyclerView) view.findViewById(R.id.rv1);
        ln2 = (LinearLayout) view.findViewById(R.id.ln2);
        tv2 = (TextView) view.findViewById(R.id.tv2);
        rv2 = (RecyclerView) view.findViewById(R.id.rv2);
        ln3 = (LinearLayout) view.findViewById(R.id.ln3);
        tv3 = (TextView) view.findViewById(R.id.tv3);
        rv3 = (RecyclerView) view.findViewById(R.id.rv3);

        ln.add(ln1);
        ln.add(ln2);
        ln.add(ln3);
    }

    private void initEvent() {
        //服务搜索
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                switch (i) {
                    case EditorInfo.IME_ACTION_SEARCH:
                        //TODO 遍历当前的服务数据，传递给Dialog显示
                        showDialog();
                        break;
                }
                return false;
            }
        });
        //服务搜索
        btSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 遍历当前的服务数据，传递给Dialog显示
                showDialog();
            }
        });
    }

    //获取所有服务
    private void getAllService() {
        //如果已经加载出数据
        if (serviceBean.size() > 0) {
            initData();
            return;
        }

        Api.config(ApiConfig.SERVICE_URL, null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                ServiceBean serviceBean = new Gson().fromJson(res, ServiceBean.class);
                if (serviceBean != null && serviceBean.getCode() == 200) {
                    AllServiceFragment.this.serviceBean = serviceBean.getRows();
                    handler.sendEmptyMessage(0x01);
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    private void initData() {
        //1 存储所有服务的类别
        for (int i = 0; i < serviceBean.size(); i++) {
            serviceTypes.add(serviceBean.get(i).getServiceType());
        }
        //2 筛选出服务类别
        //set特性就是不会重复添加同一个键
        LinkedHashSet<String> hashSet = new LinkedHashSet<>(serviceTypes);
        //3 重新转换为list 无重复服务类别数据
        serviceTypes = new ArrayList<>(hashSet);

        baseAdapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return serviceTypes.size();
            }

            @Override
            public Object getItem(int i) {
                return serviceTypes.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @SuppressLint("ViewHolder")
            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                view = LayoutInflater.from(getActivity()).inflate(R.layout.service_list_item, null, false);
                TextView tv = view.findViewById(R.id.tag);
                tv.setText(serviceTypes.get(i));
                return view;
            }
        };

        lvService.setAdapter(baseAdapter);
        //设置此属性，则在listView条目被点击时，条目背景颜色改变
        lvService.setSelector(R.color.baseGray);
        //不知道这是什么方法，乱写的
        lvService.setSelection(0);

        //左侧服务清单列表点击，右侧ScrollView滑动到指定模块
        lvService.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                scrollTo(i);
            }
        });

        setRecycle();
    }

    //ScrollView滑动方法
    private void scrollTo(int which) {
        //创建出两个存储控件宽高的数组
        int[] location = new int[2]; //ScrollView内部的View宽高
        int[] sLoc = new int[2];  //ScrollView的宽高

        //getLocationOnScreen 拿到内部控件宽高
        ln.get(which).getLocationOnScreen(location);
        //拿到 ScrollView 宽高
        sc.getLocationOnScreen(sLoc);

        //滑动距离Y 由控件的高减去ScrollView的高
        int y = location[1] - sLoc[1];

        // x方向不移动
        sc.smoothScrollBy(0, y);
    }

    //设置右侧服务列表 分别是三个线性布局包裹一个标题textview，一个服务图标recycleView 其他为装饰
    private void setRecycle() {
        //三个recycleView
        List<RecyclerView> r = new ArrayList<>();
        r.add(rv1);
        r.add(rv2);
        r.add(rv3);
        //三个线性布局
        List<TextView> t = new ArrayList<>();
        t.add(tv1);
        t.add(tv2);
        t.add(tv3);
        //遍历服务类别 取出相同服务类别的服务bean类 分别给三个recycle作为数据
        for (int j = 0; j < serviceTypes.size(); j++) {
            //临时存储同类型的bean类List
            List<ServiceBean.RowsBean> data = new ArrayList<>();
            //遍历全部服务，取出相同服务类型
            for (int i = 0; i < serviceBean.size(); i++) {
                if (serviceBean.get(i).getServiceType().equals(serviceTypes.get(j)))
                    data.add(serviceBean.get(i));
            }
            //创建适配器，设置点击数据
            ServiceRecycleAdapter adapter = new ServiceRecycleAdapter(getActivity(), data);
            adapter.setParams(params);
            //recycle设置布局方式，适配器
            r.get(j).setLayoutManager(new GridLayoutManager(getActivity(), 3));
            r.get(j).setAdapter(adapter);
            //标题textView设置当前服务类型
            t.get(j).setText(serviceTypes.get(j));
        }

    }

    //搜索 显示一个服务清单的dialog
    private void showDialog() {
        //如搜索框没有输入文字
        if (etSearch.getText().toString().trim().equals("")) {
            showToast("请输入关键词");
            return;
        }
        //获取搜索框数据
        String target = etSearch.getText().toString().trim();
        //创建临时List存储遍历数据
        List<ServiceBean.RowsBean> data = new ArrayList<>();
        //遍历所有数据，取出服务名称含有关键字的bean
        for (int i = 0; i < serviceBean.size(); i++) {
            if (serviceBean.get(i).getServiceName().contains(target)) data.add(serviceBean.get(i));
        }
        //创建弹窗 显示
        SearchServiceDialog searchServiceDialog = new SearchServiceDialog(getActivity(), data);
        searchServiceDialog.show();
    }

    class MHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x01:
                    if (serviceBean.size() > 0) {
                        initData();
                    }
                    break;
                case 0x02:
                    break;
            }
        }
    }
}